import { _decorator, Component, Prefab, instantiate, math} from 'cc';
import { GameDropAwardType } from './GameSceneUI';
const { ccclass, property } = _decorator;

@ccclass('AwardManager')
export class AwardManager extends Component {
    private static instance: AwardManager = null;

    @property([Prefab]) 
    awardPrefabList: Prefab[] = [];

    onLoad() {

        if (AwardManager.instance === null) 
        {
            AwardManager.instance = this;
        } else {
            console.error("AwardManager 已存在，请确保场景中只有一个 AwardManager");
            this.node.destroy();
        }
    }


    start() {

    }

    update(deltaTime: number) {
        
    }

    public reset() {
        // 重置单例类的状态
        AwardManager.instance = null;
    }

    public static getInstance(): AwardManager {
        return AwardManager.instance;
    }

    public CreateAward(posX,posY)
    {
        let randomNum = Math.floor(Math.random() * 100) + 1;
        if(randomNum <= 13) //概率掉落奖励
        {
            const random_award = Math.floor(math.randomRange(GameDropAwardType.Wall,GameDropAwardType.Max));
            if(this.awardPrefabList[random_award] == null)
            {
                console.error("CreateAward Erro , Index",random_award,"random_award Award Is Null");
            }
            else
            {
                //反馈一个奖励
                const award = instantiate(this.awardPrefabList[random_award]);
                if(award == null)
                {
                    console.error("award is NULL");
                }
                else
                {
                    award.setPosition(posX, posY, 0);
                
                    // 延迟一帧添加节点
                    this.scheduleOnce(() => {
                        this.node.addChild(award);
                    });

                }
            }
        }
    }
}


